import userStore from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm } from '@/utils/common'

const dictCache = new Map() // 字典内存缓存
const timeout = 10000
const baseUrl = config.baseUrl

/**
 * 获取字典数据
 * @param {string} dictType - 字典类型
 * @param {boolean} [forceRefresh=false] - 强制刷新缓存
 */
export const getDict = async (dictType, forceRefresh = false) => {
    // 优先读取缓存
    if (!forceRefresh && dictCache.has(dictType)) {
        return [...dictCache.get(dictType)] // 返回副本避免污染源数据‌:ml-citation{ref="1" data="citationList"}
    }

    try {
        const config = {
            url: `/system/dict/data/type/${dictType}`,
            method: 'GET',
            header: {
                'Content-Type': 'application/json',
                isToken: false // 默认携带token，特殊字典可配置‌:ml-citation{ref="2" data="citationList"}
            }
        }

        // Token处理逻辑
        if (config.header?.isToken !== false && getToken()) {
            config.header['Authorization'] = 'Bearer ' + getToken()
        }

        const response = await new Promise((resolve, reject) => {
            uni.request({
                url: baseUrl + config.url,
                method: config.method,
                header: config.header,
                timeout: timeout,
                success: (res) => resolve(res),
                fail: (err) => reject(err)
            })
        })

        // 状态码校验
        const code = response.data.code || 200
        const msg = errorCode[code] || response.data.msg || errorCode['default']

        if (code === 200) {
            const list = response.data.data.map(item => ({
                label: item.dictLabel,
                value: item.dictValue,
                raw: item // 保留原始数据‌:ml-citation{ref="1" data="citationList"}
            }))
            dictCache.set(dictType, list)
            return list
        } else if (code === 401) {
            showConfirm("登录状态已过期，请重新登录").then(res => {
                if (res.confirm) userStore.LogOut().then(() => uni.reLaunch({ url: '/login' }))
            })
            throw new Error('会话过期')
        } else {
            toast(msg || '字典获取失败')
            throw new Error(`[${dictType}] ${msg}`)
        }
    } catch (error) {
        console.error('字典加载异常:', error)
        throw error // 抛出错误供外部处理‌:ml-citation{ref="2" data="citationList"}
    }
}

/**
 * 获取字典标签
 * @param {string} dictType - 字典类型
 * @param {string} value - 字典值
 */
export const getDictLabel = (dictType, value) => {
    const items = dictCache.get(dictType) || []
    const target = items.find(item => item.value === value)
    return target?.label || '--'
}
